package com.lzxuni.modules.wechat.config.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.util.StringUtil;
import com.lzxuni.common.utils.StringUtils;
import com.lzxuni.common.utils.web.OkHttpUtil;
import com.lzxuni.modules.pccontrol.home.publicity.entity.Notice;
import com.lzxuni.modules.pccontrol.home.publicity.entity.Publicity;
import com.lzxuni.modules.pccontrol.home.publicity.service.NoticeService;
import com.lzxuni.modules.pccontrol.home.publicity.service.PublicityService;
import com.lzxuni.modules.wechat.config.entity.WechatUserInfo;
import com.lzxuni.modules.wechat.config.service.WeChatUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 微信登陆
 * Created by 潘云明
 * 2019/7/26 14:48
 */
@RestController
@RequestMapping("/wechat")
public class WeChatLoginController extends WeChatController {
    @Autowired
    private WeChatUserInfoService service;
    @Autowired
    private PublicityService tblHomePublicityService;
    @Autowired
    private NoticeService noticeService;

    @RequestMapping(value = "/login")
    public void authorize(HttpServletRequest request, HttpServletResponse response) throws IOException, UnsupportedEncodingException {
        //测试环境
//        String redirectURI = request.getScheme() + "://" + request.getServerName() + request.getContextPath() + "/wechat/userInfo/";
        //正式环境
        String redirectURI = URL + "/wechat/login_do";
        String state = request.getParameter("state");
        if (StringUtils.isEmpty(state)) {
            state = "";
        }
        String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + APPID + "&redirect_uri=" + (redirectURI) + "&response_type=code&scope=snsapi_userinfo&state=" + URLEncoder.encode(state, "UTF-8") + "&connect_redirect=1#wechat_redirect";
        System.out.println("请求地址为：" + url);
        response.sendRedirect(url);
    }


    @RequestMapping("/login_do")
    public ModelAndView authorize(HttpServletRequest request, String code, String state) throws IOException {
        HttpSession session = request.getSession();
        ModelAndView mv = new ModelAndView("wechat/index");
        String accessTokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + APPID + "&secret=" + APPSECRET + "&code=" + code + "&grant_type=authorization_code";
        String accessTokenResult = OkHttpUtil.httpPost(accessTokenUrl);
        System.out.println("获取用户信息用accessTokenResult:" + accessTokenResult);
        JSONObject accessTokenJsonObject = JSONObject.parseObject(accessTokenResult);
        String openid = "", nickname = "", access_token = "";
        WechatUserInfo userInfo = new WechatUserInfo();
        try {
            openid = accessTokenJsonObject.get("openid").toString();
            access_token = accessTokenJsonObject.get("access_token").toString();
            String userInfour = "https://api.weixin.qq.com/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN";
            String userInfoResult = OkHttpUtil.httpPost(userInfour);
            System.out.println("用户信息userInfoResult:" + userInfoResult.toString());
            JSONObject userInfoJsonObject = JSONObject.parseObject(userInfoResult);
            nickname = userInfoJsonObject.get("nickname").toString();
            System.out.println("得到的openid为:" + openid);
            System.out.println("得到的nickname为:" + nickname);
            System.out.println("得到的state为:" + state);
            userInfo.setOpenid(userInfoJsonObject.get("openid").toString());
            userInfo.setNickname(userInfoJsonObject.get("nickname").toString());
            userInfo.setSex(userInfoJsonObject.get("sex").toString());
            userInfo.setProvince(userInfoJsonObject.get("province").toString());
            userInfo.setCity(userInfoJsonObject.get("city").toString());
            userInfo.setCountry(userInfoJsonObject.get("country").toString());
            userInfo.setHeadimgurl(userInfoJsonObject.get("headimgurl").toString());
            if (service.getById(openid) == null || service.getById(openid).getIsboodbye().equals("1")) {
                userInfo = service.SaveOrUpdate(userInfo);
            } else {
                mv.addObject("isboodbye", "0");
            }
        } catch (Exception e) {
            System.out.println("error");
//            openid = session.getAttribute("openid").toString();
//            nickname = session.getAttribute("nickname").toString();
//            userInfo = (WechatUserInfo) session.getAttribute("userInfo");
            //潘云明--
            //alter table tbl_wechat_userinfo convert to character set utf8mb4 collate utf8mb4_bin;
            userInfo.setOpenid("oRIVq1BEyu4lPDXFX7AHI18WBfoU");
            userInfo.setNickname(" ┏ (^ω^)=☞ 营。");
            userInfo.setSex("1");
            userInfo.setProvince("黑龙江");
            userInfo.setCity("七台河");
            userInfo.setCountry("中国");
            userInfo.setHeadimgurl("http://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTI9jRwxZcwV0vX0AzibeW0laac3EfGOzzSdje0OgxXY4Hs1v77CdSjdkXchtic3LibqDKauge83CDqRA/132");
            openid = userInfo.getOpenid();
            nickname = userInfo.getNickname();
            session.setAttribute("openid", openid);
            session.setAttribute("nickname", nickname);
            session.setAttribute("userInfo", userInfo);
            //--
        }
        session.setAttribute("openid", openid);
        session.setAttribute("nickname", userInfo.getNickname());
        session.setAttribute("userInfo", userInfo);
        mv.addObject("openid", openid);
        mv.addObject("nickname", nickname);
        mv.addObject("userInfo", userInfo);
        //分享功能
        if (StringUtil.isNotEmpty(state)) {
            String[] state_Arr = state.split("_");
            ModelAndView mv1 = new ModelAndView();
            System.out.println("从分享进入微信");
            if (state_Arr.length == 1) {
                //政务大厅
                if (state_Arr[0].equals("ZWDT")) {
                    mv1.setViewName("redirect:/wechat/home/life/zwdt/affair_ZWDT");
                }
                //通知公告
                if (state_Arr[0].equals("TZGG")) {
                    mv1.setViewName("redirect:/wechat/home/notice/tongzhigogngao");
                }
                mv1.addObject("jsApiConfig", getJsAPiConfig(getAddress(request)));
                return mv1;
            }
            if (state_Arr.length == 2) {

                //通知公告
                if (state_Arr[0].equals("notice")) {
                    mv1.setViewName("redirect:/wechat/home/open/zhengWuFaBu_xx?id=" + state_Arr[1]);
                }
                //全城商家
                if (state_Arr[0].equals("QCSJ")) {
                    mv1.setViewName("redirect:/wechat/home/life/qcsj/affair_QCSJ_XQ?id=" + state_Arr[1]);
                }
                //帖子信息
                if (state_Arr[0].equals("FornumInfo")) {
                    mv1.setViewName("redirect:/wechat/forum/fornum_info?id=" + state_Arr[1]);
                }
                //养老
                if (state_Arr[0].equals("care")) {
                    mv1.setViewName("redirect:/wechat/home/aged/care_detail?id=" + state_Arr[1]);
                }
                //办事指南
                if (state_Arr[0].equals("ZwdtBszn")) {
                    mv1.setViewName("redirect:/wechat/home/life/zwdt/affair_ZWDT_bszn?id=" + state_Arr[1]);
                }
                //通知公告
                if (state_Arr[0].equals("tzgg")) {
                    mv1.setViewName("redirect:/wechat/home/notice/tongzhigogngao_xx?id=" + state_Arr[1]);
                }
                //全城商家主页
                if (state_Arr[0].equals("QCSJIndex")) {
                    System.out.println(state_Arr[2]);
                    mv1.setViewName("redirect:/wechat/home/life/qcsj/affair_QCSJ?type=" + state_Arr[1] + "&shopName=" + URLEncoder.encode(state_Arr[2], "UTF-8"));
                }

                mv1.addObject("jsApiConfig", getJsAPiConfig(getAddress(request)));
                return mv1;
            }
            if (state_Arr.length == 3) {
                //全城商家主页
                if (state_Arr[0].equals("QCSJIndex")) {
                    System.out.println(state_Arr[2]);
                    mv1.setViewName("redirect:/wechat/home/life/qcsj/affair_QCSJ?type=" + state_Arr[1] + "&shopName=" + URLEncoder.encode(state_Arr[2], "UTF-8"));
                }
                mv1.addObject("jsApiConfig", getJsAPiConfig(getAddress(request)));
                return mv1;
            }


        }
        //主页 政务发布数据  通知公告数据
        Publicity pc = new Publicity();
        List list = tblHomePublicityService.selectListfour(pc.setThistype("0"));
        Notice no = new Notice();
        List list2 = noticeService.selectListfour(no);
        System.out.println("*********" + JSON.toJSONString(list));
        mv.addObject("data", JSON.toJSONString(list));
        mv.addObject("data2", JSON.toJSONString(list2));

        return mv;
    }


}
